﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.Permission.Interface;
using Microhard.Core;
using Microhard.Permission.Models;
using System.Configuration;
using System.Web.Security;
using System.Web;
using Microhard.Core.DBUtility;
using Microhard.WeixinMP.Models;
using System.Web.Profile;

namespace Microhard.Permission.MVCFilter
{
    public class MVCFilterAtrForLogon : ActionFilterAttribute, IMvcFilter
    {
        private IUser user = IoC.Resolve<IUser>();
        private string _dataScopeactionParameterName = "scope";
        private bool _usingEmplyee = false;


        /// <summary>
        /// 接收数据权限结果的参数名称
        /// </summary>
        public string DataScopeactionParameterName
        {
            set
            {
                this._dataScopeactionParameterName = value;
            }
            get
            {
                return this._dataScopeactionParameterName;
            }
        }

        public MVCFilterAtrForLogon()
        {
            //表示作为action filter第一个执行
            this.Order = 0;
            this._usingEmplyee = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["GetEmplInfo"]);
        }
        #region IMvcFilter Members

        public void RedirectToAutoLogonPage(ActionExecutingContext filterContext)
        {
            var ad = new ViewResult();
            if (filterContext.RequestContext.HttpContext.Request.HttpMethod == "Get")
            {
                string url = filterContext.HttpContext.Request.Url.OriginalString;
                ad.ViewData["Url"] = url;
                filterContext.Result = ad;
            }
            else
            {
                ad.ViewData["Error"] = "服务是POST请求，无法自动登录";
            }
            ad.ViewName = "AutoLogon";
        }

        public void RedirectToNeedEmployInfoPage(ActionExecutingContext filterContext)
        {
            user.SignOut();
            filterContext.HttpContext.Session.Clear();
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = "此用户没有员工信息，不能登录，请联系系统管理员",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                var ad = new ViewResult();
                ad.ViewName = "NeedLogin";
                filterContext.Result = ad;
            }
        }

        public void RedirectToPage(ActionExecutingContext filterContext)
        {
            user.SignOut();
            filterContext.HttpContext.Session.Clear();
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult()
                {
                    Data = "此模块需要登录访问，请先登录",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                var ad = new ViewResult();
                ad.ViewName = "NeedLogin";
                filterContext.Result = ad;
            }
        }

        public static User GetLogonUser()
        {
            User result = null;
            MembershipUser user = Membership.GetUser(true);
            if (user == null || user.IsApproved == false || user.IsLockedOut == true || user.IsOnline == false)
            {
                return null;
            }
            LogonUserInfoCache luic = new LogonUserInfoCache();
            result = luic.GetFromCache(user.UserName);
            if (result == null)
            {
                IUser iuser = IoC.Resolve<IUser>();
                result = iuser.GetUserByName(user.UserName);
            }
            var pb = ProfileBase.Create(user.UserName);
            result.UserRealName = pb.GetPropertyValue("UserRealName").ToString();
            return result;
        }

        public static User GetLogonUserWithEmployeeInfo()
        {
            User result = null;
            MembershipUser user = Membership.GetUser(true);
            if (user == null || user.IsApproved == false || user.IsLockedOut == true || user.IsOnline == false)
            {
                return null;
            }
            LogonUserInfoCache luic = new LogonUserInfoCache();
            result = luic.GetFromCache(user.UserName);
            if (result == null)
            {
                IUser iuser = IoC.Resolve<IUser>();
                result = iuser.GetUserByName(user.UserName);
                var pb = ProfileBase.Create(user.UserName);
                result.UserRealName = pb.GetPropertyValue("UserRealName").ToString();

                IEmployeeValidator iev = IoC.Resolve<IEmployeeValidator>();
                result.EmpInfo = iev.IsExistEmployee(result.UserName);
                luic.UpdateCache(result.UserName, result);
            }
            return result;
        }

        public static void UserIsExpire(ActionExecutingContext filterContext)
        {
            MembershipUser user = Membership.GetUser();
            if (user == null || user.IsApproved == false || user.IsLockedOut == true || user.IsOnline == false)
            {
                FormsAuthentication.SignOut();
                filterContext.HttpContext.Session.Clear();
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        Data = "此模块需要登录访问，您的帐号未登录或连接超时"
                    };
                }
                else
                {
                    var ad = new ViewResult();
                    ad.ViewName = "NeedLogin";
                    filterContext.Result = ad;
                }
            }
            return;
        }
        #endregion

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            User longoUser = null;
            if (_usingEmplyee)
            {
                longoUser = GetLogonUserWithEmployeeInfo();
            }
            else
            {
                longoUser = GetLogonUser();
            }
            if (longoUser != null)
            {
                var scope = new ScopeResult();
                if (filterContext.ActionParameters.Keys.Contains(this._dataScopeactionParameterName))
                {
                    scope.CurrentUserID = longoUser.ID;
                    scope.CurrentUserName = longoUser.UserName;
                    scope.CurrentUserRealName = longoUser.UserRealName;
                    scope.CurrentUserRoleNames = longoUser.Roles.Select(s => s.RoleName).ToList();
                }

                if (longoUser.AccountMappingEmployee == true)
                {
                    EmpInfoModel info = longoUser.EmpInfo;
                    if (info == null)
                    {
                        RedirectToPage(filterContext);
                    }
                    else
                    {
                        scope.EmpInfo = info;
                    }
                }
                filterContext.ActionParameters[this._dataScopeactionParameterName] = scope;
                //为页面获得scope而设置
                filterContext.Controller.ViewData["scope"] = scope;
                return;
            }
            #region 微信用户登录
            //未登录，且从微信客户端发起申请，则认为是非会员的微信用户在请求服务
            var isFromwx = filterContext.HttpContext.Items["isFromWeixin"];
            if (isFromwx == null)
            {
                UserIsExpire(filterContext);
                return;
            }
            bool wx = bool.Parse(isFromwx.ToString());
            if (wx)
            {
                //是否使用微信关联登录
                var cfg = ConfigurationManager.AppSettings["UseAccountAsWXLogin"];
                string ConfigUserName = filterContext.HttpContext.Items["WeixinName"].ToString();
                if (longoUser != null)
                {
                    longoUser.WeixinName = ConfigUserName;
                }

                string pwd;
                bool usAnymousWxAccount = bool.Parse(cfg) == false ? true : false;
                IUser user = IoC.Resolve<IUser>();
                //使用微信帐户登录
                if (!usAnymousWxAccount)
                {
                    //此微信是否有对应的系统用户
                    string loginUserName = string.Empty;
                    IWeiXinAccount account = IoC.Resolve<IWeiXinAccount>();
                    if (account.ValidateByWeiXinUserName(ConfigUserName, out loginUserName))
                    {
                        //由于membership在页面请求处理完毕后，才会使用setcookie在浏览器中记录登录。
                        //所以必须让SignIn处理完毕，然后在页面上再跳转会原页面，这样Membership.GetUser才能获取到登录用户信息
                        user.SignIn(loginUserName, true);
                        RedirectToAutoLogonPage(filterContext);
                        return;
                    }
                    else
                    {
                        usAnymousWxAccount = true;
                    }
                }
                //使用微信匿名帐户登录
                if (usAnymousWxAccount)
                {
                    Log.Info("MVCFilterLogon", "usAnymousWxAccount:" + usAnymousWxAccount);
                    //使用微信内置账户登录
                    ConfigUserName = ConfigurationManager.AppSettings["weixinAccount"];
                    pwd = ConfigurationManager.AppSettings["weixinAccountPws"];

                    if (user.ValidatUser(ConfigUserName, pwd))
                    {
                        user.SignIn(ConfigUserName, true);
                        RedirectToAutoLogonPage(filterContext);
                        return;
                    }
                }
            }
            #endregion

            RedirectToPage(filterContext);
        }
    }
}
